<template>
  <div>
    <div class="pt-12 pb-80 text-white">
      <div class="w-240 mb-20 mx-auto">
        <div
          class="h-40 text-13 z-[2] bg-1D1D1F leading-40 px-4 relative rounded-10 flex items-center"
        >
          <div
            v-for="(item, index) in tabList"
            :key="item.value"
            class="h-full w-0 z-[2] font-bold text-center flex-1"
            @click="changeTabType(item, index)"
          >
            {{ item.label }}
          </div>
          <div
            class="bg-2F2F33 h-[calc(100%-8px)] duration-200 absolute z-1 rounded-8"
            :style="`width: calc((100% - 8px) / ${tabList.length});transform: translateX(calc(100% * ${currentTab}));`"
          />
        </div>
      </div>
      <div class="px-15 text-16 font-bold">选择类型</div>
      <div class="mt-12 mb-30">
        <NormalTabs
          :tabs="commonCategoryList"
          :active-id="commonCategoryId"
          @update:active-id="commonCategoryId = $event"
        >
          <template #item="{ tab, index, setItemRef, handleTabClick }">
            <div
              :ref="setItemRef"
              class="duration-200 mr-10 px-12 leading-28 h-28 rounded-15 text-14 flex-shrink-0"
              :class="{
                'ml-15': index === 0,
                'text-white bg-2614FF': commonCategoryId === tab.categoryId,
                'bg-2F2F33': commonCategoryId !== tab.categoryId
              }"
              @click="handleTabClick"
            >
              {{ tab.name }}
            </div>
          </template>
        </NormalTabs>
      </div>
      <div class="flex items-center px-15 mb-12">
        <div class="text-16 font-bold">主题描述</div>
        <div
          class="ml-auto relative text-13 text-999999"
          @click="handleAiTitleExampleVoList"
        >
          试试范文
        </div>
      </div>
      <div
        class="flex flex-col mx-15 py-12 px-15 h-250 rounded-10 bg-1D1D1F text-14 myField"
      >
        <van-field
          v-model="themeDescription"
          rows="10"
          autosize
          type="textarea"
          maxlength="500"
          :placeholder="currentCategory.remark || '例如：写一篇100字鸡汤文'"
        />
        <div class="flex items-center mt-10">
          <div class="relative text-999999" @click="themeDescription = ''">
            清空
          </div>
          <div class="ml-auto text-666666">
            {{ themeDescription.length }}/500
          </div>
        </div>
      </div>
      <div
        class="py-15 w-full van-nav-bar--fixed !top-auto bottom-0 flex items-center"
      >
        <div
          class="flex flex-col justify-center items-center px-15"
          @click="navigateTo('AiCopyGenHistory')"
        >
          <svg-icon name="icon-lishijilu" :size="18" color="#fff" />
          <div class="mt-6 text-11">历史记录</div>
        </div>
        <div class="flex-1 mr-15">
          <ButtonFooter @confirm="handleCreateAiText">
            <div class="text-white font-bold w-full">生成</div>
            <div v-if="tabType == AI_COPY_MODEL_ENUM.DEEPSEEK" class="text-13">
              （消耗1个AI币）
            </div>
          </ButtonFooter>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { AI_COPY_MODEL_ENUM, IMG_CDN_39 } from "@/constants";
import { computed, onMounted, ref, watch } from "vue";
import NormalTabs from "@/components/NormalTabs/index.vue";
import {
  AiTitleExampleVoInfoData,
  CommonCategoryInfoData,
  createAiText,
  getAiTitleExampleVoList,
  getCommonCategoryList
} from "@/api/AiCopyGenerator";
import router from "@/router";
import { showToast } from "vant";
import { useRoute } from "vue-router";
import { getLocalStorage, removeLocalStorage, setLocalStorage } from "@/utils";

defineOptions({
  name: "AiCopyGenerator"
});
const route = useRoute();
// 直接使用计算属性获取参数
const routeName = ref(route.params.routeName as string);
// 当前Tabs索引
const currentTab = ref(1);
// 切换大模型类型
interface ModelTab {
  label: string;
  value: number;
}
const changeTabType = (item: ModelTab, index: number) => {
  currentTab.value = index;
  tabType.value = item.value;
};
// 大模型类型Tabs
const tabList: ModelTab[] = [
  { label: "Deepseek", value: AI_COPY_MODEL_ENUM.DEEPSEEK },
  { label: "Hunyuan", value: AI_COPY_MODEL_ENUM.HUNYUAN }
];
// 分类请求列表
const commonCategoryList = ref<CommonCategoryInfoData[]>([]);
// 分类ID
const commonCategoryId = ref("");
// 根据commonCategoryId计算获取commonCategoryList对应的对象
const currentCategory = computed(() => {
  return (
    commonCategoryList.value.find(
      item => item.categoryId === commonCategoryId.value
    ) || { categoryId: "", name: "", remark: "", sort: 0, type: 0, id: "" }
  );
});
// 主题描述
const themeDescription = ref("");
// 当前大模型类型
const tabType = ref(AI_COPY_MODEL_ENUM.HUNYUAN);
//  模板信息列表
const handleCreateAiText = async () => {
  if (themeDescription.value.length === 0) {
    showToast("请输入主题描述");
    return;
  }
  const param = {
    modelType: tabType.value,
    title: themeDescription.value
  };
  const aiTextId = await createAiText(param);
  if (aiTextId) {
    if (routeName.value) {
      setLocalStorage("AiCopyGenHistory_AiTextId", aiTextId);
      const templateId = getLocalStorage("CreatePictureVideo_TemplateId");
      const routerParam = { id: "" };
      if (templateId) {
        removeLocalStorage("CreatePictureVideo_TemplateId");
        routerParam.id = templateId as string;
      }
      await router.push({
        name: routeName.value,
        params: routerParam.id ? routerParam : {}
      });
    } else {
      navigateTo("AiCopyGenHistory");
    }
  }
};
// 导航到指定页面
const navigateTo = (routeName: string) => {
  router.push({ name: routeName });
};
// 添加ai范文列表
const aiTitleExampleVoList = ref<AiTitleExampleVoInfoData[]>([]);
const aiTitleExampleVoNum = ref(0);
const handleAiTitleExampleVoList = async () => {
  if (
    aiTitleExampleVoNum.value == 0 &&
    aiTitleExampleVoList.value.length === 0
  ) {
    aiTitleExampleVoList.value = await getAiTitleExampleVoList({
      categoryId: commonCategoryId.value
    });
  }
  themeDescription.value =
    aiTitleExampleVoList.value[aiTitleExampleVoNum.value].title;
  aiTitleExampleVoNum.value++;
  if (aiTitleExampleVoNum.value == aiTitleExampleVoList.value.length) {
    aiTitleExampleVoNum.value = 0;
  }
};
// 添加监听commonCategoryId变化的逻辑
watch(commonCategoryId, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    // 当commonCategoryId变化时，重置aiTitleExampleVoList和aiTitleExampleVoNum
    aiTitleExampleVoList.value = [];
    aiTitleExampleVoNum.value = 0;
  }
});
// 分类请求接口
const getCommonCategoryListPort = async () => {
  const commonCategoryResult = await getCommonCategoryList({ categoryType: 5 });
  commonCategoryList.value = commonCategoryResult.map(item => ({
    ...item,
    id: item.categoryId
  }));
  if (commonCategoryList.value.length) {
    commonCategoryId.value = commonCategoryList.value[0].categoryId;
  }
};
onMounted(() => {
  getCommonCategoryListPort();
});
</script>
<style scoped>
.myField .van-cell {
  background-color: transparent;
  padding: 0;
  border: 0;
}
.myField .van-cell:after {
  border: 0;
}
</style>
